import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.websocket.*;


public class WebSocketClient extends Endpoint{

    private static final String SERVER_URI = "ws://localhost:38080/jeecg-boot/websocket/file/1680863542425743361";
    private static final long PING_INTERVAL = 10;

    private Session session;

    @Override
    public void onOpen(Session session, EndpointConfig endpointConfig) {
        System.out.println("Connected to server: " + session.getId());
        this.session = session;
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(() -> sendPing(), 0, PING_INTERVAL, TimeUnit.SECONDS);
        session.addMessageHandler(new MessageHandler.Whole<String>() {
            @Override
            public void onMessage(String message) {
                System.out.println("Received message: " + message);
            }
        });
    }

    private void sendPing() {
        try {
            System.out.println("Sending ping...");
            this.session.getBasicRemote().sendText("ping");
        } catch (IOException e) {
            System.out.println("Error sending ping: " + e.getMessage());
        }
    }

    @Override
    public void onClose(Session session, CloseReason closeReason) {
        System.out.println(closeReason.getReasonPhrase());
    }

    @Override
    public void onError(Session session, Throwable thr) {
        System.out.println(thr.getMessage());
    }


    public static void main(String[] args) {
        try {
            ClientEndpointConfig.Configurator configurator = new ClientEndpointConfig.Configurator() {
                @Override
                public void beforeRequest(Map<String, List<String>> headers) {
                    super.beforeRequest(headers);
                    String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MDY2ODA0MDIsInVzZXJuYW1lIjoibHlzIn0.voaEkdL2PilzYzKGEr2y4o98PvK3Iz9ELtmh-Ivkfac";
                    headers.put("Sec-WebSocket-Protocol",Arrays.asList(token));
                }
            };
            ClientEndpointConfig config = ClientEndpointConfig.Builder.create().configurator(configurator).build();
            javax.websocket.WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            Session session = container.connectToServer(WebSocketClient.class,config, new URI(SERVER_URI));
            session.getBasicRemote().sendText("Hello, WebSocket Server!");
            // 无限循环，保持客户端处于活动状态
            while (true) {
                Thread.sleep(1000); // 可以适当调整睡眠时间
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
